﻿using Furion;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using JoyAdmin.Core.Model;
using JoyAdmin.Core;
using DX_Common.AgreementEntity;
using DX_Common.Common;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Data;
using System.Threading;
using DX_Common.Model;
using Microsoft.AspNetCore.Http;
using System.Net.Sockets;
using System.Net;
using System.Text;
using Furion.DatabaseAccessor;
using Mapster;
using System.Data.Common;
using Furion.DatabaseAccessor.Extensions;

namespace JoyAdmin.Application
{
    /// <summary>
    /// 渔业服务
    /// </summary>
    public class FisheryService : IDynamicApiController
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IAuthorizationManager _authorizationManager;
        private readonly IRepository<Fishery_quyu> _Fishery_quyu;
        private readonly IRepository<Fishery_chitang> _Fishery_chitang;
        private readonly IRepository<Fishery_device> _Fishery_device;
        private readonly IRepository<Fishery_alarm> _Fishery_alarm;
        public FisheryService(IHttpContextAccessor httpContextAccessor
            , IAuthorizationManager authorizationManager
            , IRepository<Fishery_quyu> Fishery_quyu
            , IRepository<Fishery_chitang> Fishery_chitang
            , IRepository<Fishery_device> Fishery_device
            , IRepository<Fishery_alarm> Fishery_alarm
            ) 
        {
            _httpContextAccessor = httpContextAccessor;
            _authorizationManager = authorizationManager;
            _Fishery_quyu = Fishery_quyu;
            _Fishery_chitang = Fishery_chitang;
            _Fishery_device = Fishery_device;
            _Fishery_alarm = Fishery_alarm;
        }

        /// <summary>
        /// 查询区域列表
        /// </summary>
        public List<Fishery_quyu> GetquyuListByUserid()
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();

            var roles = _Fishery_quyu
              .Where(u => u.user_id == userId);
            return roles.Adapt<List<Fishery_quyu>>();
        }

        /// <summary>
        /// 查询池塘列表
        /// </summary>
        public List<Fishery_chitang> GetchitangListByUserid()
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();

            var roles = _Fishery_chitang
              .Where(u => u.user_id == userId);
            return roles.Adapt<List<Fishery_chitang>>();
        }

        public Task SaveChiTang(Fishery_chitang input)
        {
            var userId = _authorizationManager.GetUserId();
            input.user_id = userId;
            if (string.IsNullOrWhiteSpace(input.id))
            {
                return _Fishery_chitang.InsertAsync(input.Adapt<Fishery_chitang>());
            }
            else
            {
                return _Fishery_chitang.UpdateAsync(input.Adapt<Fishery_chitang>());
            }
        }

        /// <summary>
        /// 查询设备列表
        /// </summary>
        public List<Fishery_device> GetdeviceListByChitangId(Fishery_device input)
        {
            var roles = _Fishery_device
              .Where(u => u.chitangname == input.chitangname).Adapt<List<Fishery_device>>();
            while (roles.Count()<4)
            {
                roles.Add(input);
            }
            return roles;
        }

        public void SaveTerminalPort(List<Fishery_device> Linput)
        {
            for (int i = 0; i < Linput.Count; i++)
            {
                if (string.IsNullOrWhiteSpace(Linput[i].devicename))
                    continue;

                if (string.IsNullOrWhiteSpace(Linput[i].id))
                {
                    _Fishery_device.InsertAsync(Linput[i].Adapt<Fishery_device>());
                }
                else
                {
                    _Fishery_device.UpdateAsync(Linput[i].Adapt<Fishery_device>());
                }
            }
        }

        /// <summary>
        /// 查询设备列表 联合查询从池塘表
        /// </summary>
        public List<Fishery_deviceDto> GetdeviceListByUserid()
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();

            return "select de.*,quyuid from Fishery_device de inner join Fishery_chitang ct on ct.id=de.chitangname where ct.user_id=@id".SqlQuery<Fishery_deviceDto>(new { id = userId });
        }


        /// <summary>
        /// 查询报警列表
        /// </summary>
        public List<Fishery_alarm> GetalarmListByUserid()
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();

            var roles = _Fishery_alarm
              .Where(u => u.user_id == userId);
            return roles.Adapt<List<Fishery_alarm>>();
        }

        public Task UpdalarmState_m(Fishery_alarm input)
        {
            var userId = _authorizationManager.GetUserId();
            input.user_id = userId;
            input.status = false;
            if (string.IsNullOrWhiteSpace(input.id))
            {
                return _Fishery_alarm.InsertAsync(input.Adapt<Fishery_alarm>());
            }
            else
            {
                return _Fishery_alarm.UpdateAsync(input.Adapt<Fishery_alarm>());
            }
        }

        /// <summary>
        /// 查询自动化列表
        /// </summary>
        public List<Fishery_alarm> GetauomationListByUserid()
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();

            var roles = _Fishery_alarm
              .Where(u => u.user_id == userId);
            return roles.Adapt<List<Fishery_alarm>>();
        }

        /// <summary>
        /// 刷新模拟协议报文
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string EditForwardRefreshMessage(TransDevice input)
        {
            // 找协议
            String AgreementName = Convert.ToString(input.AgreeName.Replace("\r\n", "")); //sl651
            Type t = AgreementLoad.ListAgreementClass.Where(x => x.Name == AgreementName).FirstOrDefault();
            if (t == null)
            {
                throw Oops.Oh(ErrorCode.WrongValidation, "未找到协议类:" + AgreementName).StatusCode(ErrorStatus.ValidationFaild);
            }

            try
            {
                //加载实例化协议
                var tmpClass = (IbaseAgreement)Activator.CreateInstance(t);

                List<EssDataModelJSON> listModel = new List<EssDataModelJSON>();
                EssDataModelJSON essDataModel = new EssDataModelJSON();
                essDataModel.ST = input.DeviceNo;
                essDataModel.TT = "2024-09-09 11:20:00.000";
                essDataModel.TYPE = "OVERTIME";
                essDataModel.SERIAL = 2023;
                essDataModel.TELTYPE = 1;
                essDataModel.ESS = "Z";
                essDataModel.SDATA = "3.141";
                essDataModel.DATA = 3.141;
                essDataModel.UT = "2024-09-09 11:25:50.000";
                essDataModel.STT = "2024-09-09 11:39:07.587";
                listModel.Add(essDataModel);

                DataTable namesTable = new DataTable();
                namesTable.Columns.Add("Agreement_Json");
                namesTable.Columns.Add("ExternalDeviceNo");
                namesTable.Columns.Add("DeviceNo");
                namesTable.Columns.Add("EssCode");

                DataRow rwpz = namesTable.NewRow();
                rwpz["Agreement_Json"] = input.AgreeMent_Json;
                rwpz["ExternalDeviceNo"] = input.ExternalDeviceNo;
                rwpz["DeviceNo"] = input.DeviceNo;
                rwpz["EssCode"] = input.EssCode;


                // 判断发送类型
                switch (tmpClass.Transfertype)
                {
                    case AgreementTransferype.tcp:
                    case AgreementTransferype.udp:
                        //拼接发送数据 写入参数
                        Tuple<bool, Byte[]> tfmessage = tmpClass.SplicedSendMessage<Byte[]>(rwpz, listModel);
                        if (tfmessage.Item1)
                        {
                            return (TransData.ConvertDataBySpace(tfmessage.Item2));
                          
                        }
                        break;
                    case AgreementTransferype.httpPost:
                        //拼接发送数据 写入参数
                        Tuple<bool, string> tfmessage1 = tmpClass.SplicedSendMessage<string>(rwpz, listModel);
                        if (tfmessage1.Item1)
                        {
                            return (tfmessage1.Item2);

                        }
                        break;
                    case AgreementTransferype.mqtt:
                        break;
                    case AgreementTransferype.ftp:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ErrorCode.WrongValidation, ex.ToString()).StatusCode(ErrorStatus.ValidationFaild);
            }
            return "";
        }


        public static Socket blOpenTcpClient(string ipString, int port)
        {
            Socket clientSocket = null;
            //连接
            try
            {
                IPAddress ip = IPAddress.Parse(ipString);
                IPEndPoint remoteEndPoint = new IPEndPoint(ip, port);
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.SendTimeout = 2000;     //2s内，要求数据包发出
                clientSocket.ReceiveTimeout = 2000;  //2s内，要求应答消息收到

                try
                {
                    clientSocket.Connect(remoteEndPoint);
                    return clientSocket;
                }
                catch (Exception ex)
                {
                    //Messages.SaveLog(ex);
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }


    }

}